import { useEditor } from '@craftjs/core';
import { Dropdown, type MenuProps } from 'antd';
import React, { useEffect, useMemo } from 'react';
import styled from 'styled-components';
import { DragItem } from '../DragItem';

type NodeBoxProps = {
  id: string;
  children?: React.ReactNode;
  style?: React.CSSProperties;
};

const NodeBoxStyle = styled.div`
  position: relative;

  /* &::after {
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    border: 1px solid transparent;
    border-color: var(--border-color);
  } */

  [data-border] {
    position: absolute;
    border-color: var(--border-color);
    border-style: solid;
    border-width: 0;
    z-index: 9;
  }

  [data-border='left'] {
    left: 0;
    top: 0;
    bottom: 0;
    border-left-width: 1px;
  }

  [data-border='top'] {
    left: 0;
    top: 0;
    right: 0;
    border-top-width: 1px;
  }

  [data-border='right'] {
    right: 0;
    top: 0;
    bottom: 0;
    border-right-width: 1px;
  }

  [data-border='bottom'] {
    left: 0;
    bottom: 0;
    right: 0;
    border-bottom-width: 1px;
  }
`;

export const NodeBox: React.FC<NodeBoxProps> = ({ id, children, style }) => {
  const {
    selected,
    preview,
    hovered,
    actions: { delete: deleteNode, selectNode },
  } = useEditor((state) => {
    const [selected] = Array.from(state.events.selected);
    const [hovered] = Array.from(state.events.hovered);

    return {
      selected: selected === id,
      preview: state.options.enabled,
      hovered: hovered === id,
    };
  });

  const items: MenuProps['items'] = [
    {
      label: 'Delete',
      key: 'DELETE',
      onClick() {
        deleteNode(id);
      },
    },
  ];

  const outline = useMemo(() => {
    if (selected) {
      return '#4096ff';
    }

    return hovered ? '#ff4d4f' : 'transparent';
  }, [selected, hovered]);

  useEffect(() => {
    selectNode(id);
  }, []);

  return preview ? (
    <Dropdown menu={{ items }} trigger={['contextMenu']}>
      <NodeBoxStyle
        style={
          {
            '--border-color': outline,
            ...style,
          } as any
        }
        onContextMenu={(e) => {
          e.stopPropagation();
        }}
      >
        <div data-border="left" />
        <div data-border="right" />
        <div data-border="top" />
        <div data-border="bottom" />
        <DragItem style={style}>{children}</DragItem>
      </NodeBoxStyle>
    </Dropdown>
  ) : (
    <DragItem>{children}</DragItem>
  );
};
